package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.device.DeviceQuery;
import com.uzai.console.dto.feign.uzaicms.CmsDtkTbGoodsDetailDto;
import com.uzai.console.dto.feign.uzaicms.CmsTbGoodsSuperSearchDto;
import com.uzai.console.dto.feign.uzaicms.CmsTbGoodsTypeSearchDto;
import com.uzai.console.dto.pyq.pyqgoods.PyqJobBatchSendDao;
import com.uzai.console.dto.pyq.pyqgoods.PyqJobSendDao;
import com.uzai.console.dto.pyq.pyqgoods.PyqTbGoodsQuery;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.dto.wechatwork.devicewxworkinfo.DeviceWxworkInfoQuery;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.DeviceWxworkInfo;
import com.uzai.console.entity.PyqDevicePlan;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.mapper.DeviceWxworkInfoMapper;
import com.uzai.console.mapper.PyqDevicePlanMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiCmsFeignService;
import com.uzai.console.service.pyq.PyqDevicePlanService;
import com.uzai.console.service.pyq.PyqGoodsService;
import com.uzai.console.service.pyq.PyqGoodsSyncService;
import com.uzai.console.vo.cms.tbgoods.CmsTbGoodsFirstTypeVo;
import com.uzai.console.vo.cms.tbgoods.CmsTbGoodsInfoVo;
import com.uzai.console.vo.cms.tbgoods.DtkGoodsDetailVo;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.feign.uzaicms.SupperSearchVo;
import com.uzai.console.vo.feign.uzaicms.TypeSearchVo;
import com.uzai.console.vo.pyq.pyqgoods.PyqTbGoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

/**
 * 朋友圈商品列表
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqGoodsServiceImpl implements PyqGoodsService {

    Logger logger = LoggerFactory.getLogger(PyqGoodsServiceImpl.class);

    @Autowired
    private UzaiCmsFeignService uzaiCmsFeignService;
    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;
    @Autowired
    private PyqGoodsSyncService pyqGoodsSyncService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private PyqDevicePlanService pyqDevicePlanService;

    /**
     * 查询朋友圈淘宝商品列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqTbGoodsQuery
     * @return null
     */
    public Page<PyqTbGoodsVo> findPyqTbGoodsList(PyqTbGoodsQuery pyqTbGoodsQuery){
        //执行分页查询对象
        Page<PyqTbGoodsVo> pageVo = new Page<>();
        pyqTbGoodsQuery.convert(pageVo);

        //新建返回到页面的LIST对象
        List<PyqTbGoodsVo> pyqTbGoodsVoList = new ArrayList<>();
        //分页标识（默认从1开始）
        Long  totalNum = null;

        //有关键字，超级搜索
        if(StringUtils.isNotBlank(pyqTbGoodsQuery.getKeyword())){
            //请求接口-超级搜索
            CmsTbGoodsSuperSearchDto cmsTbGoodsSuperSearchDto = new CmsTbGoodsSuperSearchDto();

            //关键字
            if(StringUtils.isNotBlank(pyqTbGoodsQuery.getKeyword())){
                cmsTbGoodsSuperSearchDto.setKeyword(pyqTbGoodsQuery.getKeyword());
            }
            //分页
            if(pyqTbGoodsQuery.getCurrent() != null){
                cmsTbGoodsSuperSearchDto.setMin_id(String.valueOf(pyqTbGoodsQuery.getCurrent()));
            }
            //每页条数
            cmsTbGoodsSuperSearchDto.setSize(50);
            //券后价下限
            if(pyqTbGoodsQuery.getMinPrice() != null){
                cmsTbGoodsSuperSearchDto.setMinPrice(pyqTbGoodsQuery.getMinPrice());
            }
            //券后价上限
            if(pyqTbGoodsQuery.getMaxPrice() != null){
                cmsTbGoodsSuperSearchDto.setMaxPrice(pyqTbGoodsQuery.getMaxPrice());
            }

            //排序
            if(pyqTbGoodsQuery.getSort() != null){
                cmsTbGoodsSuperSearchDto.setSort(pyqTbGoodsQuery.getSort());
            }

            UzaiRespVo<SupperSearchVo> uzaiRespVo = uzaiCmsFeignService.superSearch(cmsTbGoodsSuperSearchDto);

            logger.info("--调用大淘客超级搜素接口微服务接口--dto={}", JSONObject.toJSONString(cmsTbGoodsSuperSearchDto));

            if(uzaiRespVo.getCode() == 200){
                if(uzaiRespVo.getData() != null){
                    List<CmsTbGoodsInfoVo> cmsTbGoodsInfoVoList = uzaiRespVo.getData().getData();
                    if(cmsTbGoodsInfoVoList != null && cmsTbGoodsInfoVoList.size() > 0){
                        for (CmsTbGoodsInfoVo cmsTbGoodsInfoVo : cmsTbGoodsInfoVoList){
                            PyqTbGoodsVo pyqTbGoodsVo = new PyqTbGoodsVo();
                            if(cmsTbGoodsInfoVo != null){
                                BeanUtils.copyProperties(cmsTbGoodsInfoVo, pyqTbGoodsVo);
                                pyqTbGoodsVoList.add(pyqTbGoodsVo);
                            }
                        }

                        // ForkJoinPool 的默认线程数量为系统核心数
                        ForkJoinPool forkJoinPool = new ForkJoinPool(3); //3个线程
                        forkJoinPool.submit(() -> {
                            // 使用并发流来处理，另外，这也是常用的修改parallelStream线程数方法
                            Collections.synchronizedList(pyqTbGoodsVoList).parallelStream().forEach(pyqTbGoodsVo -> {
                                try {
                                    CmsDtkTbGoodsDetailDto cmsDtkTbGoodsDetailDto = new CmsDtkTbGoodsDetailDto();
                                    cmsDtkTbGoodsDetailDto.setItemId(pyqTbGoodsVo.getItemid());
                                    UzaiRespVo<DtkGoodsDetailVo> uzaiRespVo1 = uzaiCmsFeignService.dtkGoodsDetailSingle(cmsDtkTbGoodsDetailDto);
                                    if(uzaiRespVo1.getCode() == 200 ) {
                                        DtkGoodsDetailVo dtkGoodsDetailVo = uzaiRespVo1.getData();
                                        if (dtkGoodsDetailVo != null) {
                                            //轮播图
                                            pyqTbGoodsVo.setImgs(dtkGoodsDetailVo.getImgs());
                                            //文案
                                            pyqTbGoodsVo.setDesc(dtkGoodsDetailVo.getDesc());
                                            //封装页面显示的所有图片列表
                                            List<String> allImgList = new ArrayList<>();
                                            //添加营销主图
                                            if(StringUtils.isNotBlank(dtkGoodsDetailVo.getMarketingMainPic())){
                                                allImgList.add(dtkGoodsDetailVo.getMarketingMainPic());
                                            }
                                            if(StringUtils.isNotBlank(dtkGoodsDetailVo.getMainPic())){
                                                //添加商品主图
                                                allImgList.add(dtkGoodsDetailVo.getMainPic());
                                            }

                                            //添加轮播图
                                            String lunboImgs = Tools.getStr(dtkGoodsDetailVo.getImgs());
                                            String[] lunboImgList = lunboImgs.split(",");
                                            if(lunboImgList != null && lunboImgList.length > 0){
                                                for (String lunboImg : lunboImgList){
                                                    if(StringUtils.isNotBlank(lunboImg)){
                                                        allImgList.add(lunboImg);
                                                    }
                                                }
                                            }
                                            if(allImgList.size() > 9){
                                                allImgList = allImgList.subList(0, 9);
                                            }
                                            pyqTbGoodsVo.setAllImgList(allImgList);
                                        }

                                    }
                                }catch (Exception e){
                                }
                            });
                        }).join();

                        forkJoinPool.shutdown();

                    }
                    totalNum = uzaiRespVo.getData().getTotalNum();
                }
            }
        }else{ //否则普通搜索

            //请求接口-普通搜索
            CmsTbGoodsTypeSearchDto cmsTbGoodsTypeSearchDto = new CmsTbGoodsTypeSearchDto();

            //分页
            if(pyqTbGoodsQuery.getCurrent() != null){
                cmsTbGoodsTypeSearchDto.setMin_id(String.valueOf(pyqTbGoodsQuery.getCurrent()));
            }
            //每页条数
            cmsTbGoodsTypeSearchDto.setSize(50);
            //类目
            if(pyqTbGoodsQuery.getCid() != null){
                cmsTbGoodsTypeSearchDto.setCid(pyqTbGoodsQuery.getCid());
            }
            //券后价下限
            if(pyqTbGoodsQuery.getMinPrice() != null){
                cmsTbGoodsTypeSearchDto.setMinPrice(pyqTbGoodsQuery.getMinPrice());
            }
            //券后价上限
            if(pyqTbGoodsQuery.getMaxPrice() != null){
                cmsTbGoodsTypeSearchDto.setMaxPrice(pyqTbGoodsQuery.getMaxPrice());
            }

            //排序参数字段（0-综合排序，1-销量从高到低，2-销量从低到高，3-佣金比例从低到高，4-佣金比例从高到低，5-价格从高到低，6-价格从低到高）
            //普通查询排序（0-综合排序，2-销量从高到低，4-佣金比例从高到低，5-价格（券后价）从高到低，6-价格（券后价）从低到高）
            //超级搜索排序：与排序参数字段一样，故不修改
            if(pyqTbGoodsQuery.getSort() != null){
                if(pyqTbGoodsQuery.getSort().intValue() == 0){
                    cmsTbGoodsTypeSearchDto.setSort(0);
                }else if(pyqTbGoodsQuery.getSort().intValue() == 1){
                    cmsTbGoodsTypeSearchDto.setSort(2);
                }else if(pyqTbGoodsQuery.getSort().intValue() == 4){
                    cmsTbGoodsTypeSearchDto.setSort(4);
                }else if(pyqTbGoodsQuery.getSort().intValue() == 5){
                    cmsTbGoodsTypeSearchDto.setSort(5);
                }else if(pyqTbGoodsQuery.getSort().intValue() == 6){
                    cmsTbGoodsTypeSearchDto.setSort(6);
                }
            }

            UzaiRespVo<TypeSearchVo> uzaiRespVo = uzaiCmsFeignService.typeSearch(cmsTbGoodsTypeSearchDto);

            logger.info("--调用大淘客查询商品列表微服务接口--dto={}", JSONObject.toJSONString(cmsTbGoodsTypeSearchDto));

            if(uzaiRespVo.getCode() == 200){
                if(uzaiRespVo.getData() != null){
                    List<CmsTbGoodsInfoVo> cmsTbGoodsInfoVoList = uzaiRespVo.getData().getData();

                    //logger.info(JSONObject.toJSONString(cmsTbGoodsInfoVoList));

                    if(cmsTbGoodsInfoVoList != null && cmsTbGoodsInfoVoList.size() > 0){
                        for (CmsTbGoodsInfoVo cmsTbGoodsInfoVo : cmsTbGoodsInfoVoList){
                            PyqTbGoodsVo pyqTbGoodsVo = new PyqTbGoodsVo();
                            if(cmsTbGoodsInfoVo != null){
                                BeanUtils.copyProperties(cmsTbGoodsInfoVo, pyqTbGoodsVo);
                                pyqTbGoodsVoList.add(pyqTbGoodsVo);
                            }
                        }

                        // ForkJoinPool 的默认线程数量为系统核心数
                        ForkJoinPool forkJoinPool = new ForkJoinPool(3); //3个线程
                        forkJoinPool.submit(() -> {
                            // 使用并发流来处理，另外，这也是常用的修改parallelStream线程数方法
                            Collections.synchronizedList(pyqTbGoodsVoList).parallelStream().forEach(pyqTbGoodsVo -> {
                                try {
                                    CmsDtkTbGoodsDetailDto cmsDtkTbGoodsDetailDto = new CmsDtkTbGoodsDetailDto();
                                    cmsDtkTbGoodsDetailDto.setItemId(pyqTbGoodsVo.getItemid());
                                    UzaiRespVo<DtkGoodsDetailVo> uzaiRespVo1 = uzaiCmsFeignService.dtkGoodsDetailSingle(cmsDtkTbGoodsDetailDto);
                                    if(uzaiRespVo1.getCode() == 200 ) {
                                        DtkGoodsDetailVo dtkGoodsDetailVo = uzaiRespVo1.getData();
                                        if (dtkGoodsDetailVo != null) {
                                            //轮播图
                                            pyqTbGoodsVo.setImgs(dtkGoodsDetailVo.getImgs());
                                            //文案
                                            pyqTbGoodsVo.setDesc(dtkGoodsDetailVo.getDesc());
                                            //封装页面显示的所有图片列表
                                            List<String> allImgList = new ArrayList<>();
                                            //添加营销主图
                                            if(StringUtils.isNotBlank(dtkGoodsDetailVo.getMarketingMainPic())){
                                                allImgList.add(dtkGoodsDetailVo.getMarketingMainPic());
                                            }
                                            //添加商品主图
                                            if(StringUtils.isNotBlank(dtkGoodsDetailVo.getMainPic())){
                                                allImgList.add(dtkGoodsDetailVo.getMainPic());
                                            }

                                            //添加轮播图
                                            String lunboImgs = Tools.getStr(dtkGoodsDetailVo.getImgs());
                                            String[] lunboImgList = lunboImgs.split(",");
                                            if(lunboImgList != null && lunboImgList.length > 0){
                                                for (String lunboImg : lunboImgList){
                                                    //添加商品主图
                                                    if(StringUtils.isNotBlank(lunboImg)){
                                                        allImgList.add(lunboImg);
                                                    }
                                                }
                                            }
                                            if(allImgList.size() > 9){
                                                allImgList = allImgList.subList(0, 9);
                                            }
                                            pyqTbGoodsVo.setAllImgList(allImgList);
                                        }
                                    }
                                }catch (Exception e){
                                }
                            });
                        }).join();

                        forkJoinPool.shutdown();

                    }
                    totalNum = Tools.getLong(uzaiRespVo.getData().getTotalNum());
                }
            }
        }

        //返回到页面分页对象
        pageVo.setRecords(pyqTbGoodsVoList);
        pageVo.setTotal(totalNum);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }


    /**
     * 查询官方大淘客淘宝商品一级类目列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return CmsTbGoodsInfoVo
     */
    public List<CmsTbGoodsFirstTypeVo> findCmsTbGoodsFirstTypeList(){

        //新建返回到页面的LIST对象
        List<CmsTbGoodsFirstTypeVo> cmsTbGoodsFirstTypeVoList = new ArrayList<>();

        UzaiRespVo<List<CmsTbGoodsFirstTypeVo>> uzaiRespVo =  uzaiCmsFeignService.firstTypeList();
        if(uzaiRespVo.getCode() == 200){
            if(uzaiRespVo.getData() != null){
                cmsTbGoodsFirstTypeVoList = uzaiRespVo.getData();
            }
        }
        //将分页信息复制到返回到页面的分页MO当中
        return cmsTbGoodsFirstTypeVoList;
    }

    /**
     * 批量发送朋友任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void batchSendPyqJpb(PyqJobBatchSendDao pyqJobBatchSendDao){
        if(pyqJobBatchSendDao.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqJobBatchSendDao.getDevicePlanId(), pyqJobBatchSendDao.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        //检验该设备方案是否能正常发送朋友圈
//        if(!pyqDevicePlanService.validatePyqDevicePlan(pyqDevicePlan)){
//            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案配置的机器人联盟和pid不能转链");
//        }

        if(pyqDevicePlan.getDeviceModel() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发送机器人模式");
        }

        //发送朋友圈的机器人列表
        List<Long> deviceUniqueIdList = null;
        if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
            //验证发送机器人
            deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
        }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(pyqDevicePlan.getMerId());
            deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                deviceUniqueIdList = new ArrayList<>();
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    deviceUniqueIdList.add(deviceInfoVo.getId());
                }
            }
        }

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置机器人");
        }

        pyqJobBatchSendDao.setType(0); //默认商品
        pyqJobBatchSendDao.setPlatform(0); //默认淘宝
        pyqJobBatchSendDao.setDomain(pyqDevicePlan.getDomain());

        List<String> itemidList = pyqJobBatchSendDao.getItemidList();
        if(itemidList == null || itemidList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择商品");
        }

        if(itemidList.size() > 1){ //批量发送，需要设置时间间隔
            if(pyqJobBatchSendDao.getTimeInterval() == null){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入间隔时间");
            }

            if(pyqJobBatchSendDao.getTimeInterval() < 1 || pyqJobBatchSendDao.getTimeInterval() > 1440 ){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "间隔时间范围在1~1440分钟之内");
            }
        }

        //后台异步调用批量发送朋友圈接口
        pyqGoodsSyncService.batchAddJobSync(pyqJobBatchSendDao, deviceUniqueIdList);

        try{
            Thread.sleep(500);
        }catch (Exception e){

        }
    }

    /**
     * 单个商品发送朋友任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void sendPyqJpb(PyqJobSendDao pyqJobSendDao){
        if(pyqJobSendDao.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqJobSendDao.getDevicePlanId(), pyqJobSendDao.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        //检验该设备方案是否能正常发送朋友圈
//        if(!pyqDevicePlanService.validatePyqDevicePlan(pyqDevicePlan)){
//            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案配置的机器人联盟和pid不能转链");
//        }

        if(pyqDevicePlan.getDeviceModel() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发送机器人模式");
        }

        //发送朋友圈的机器人列表
        List<Long> deviceUniqueIdList = null;
        if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
            //验证发送机器人
            deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
        }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(pyqDevicePlan.getMerId());
            deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                deviceUniqueIdList = new ArrayList<>();
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    deviceUniqueIdList.add(deviceInfoVo.getId());
                }
            }
        }

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置机器人");
        }

        pyqJobSendDao.setType(0); //默认商品
        pyqJobSendDao.setPlatform(0); //默认淘宝
        pyqJobSendDao.setDomain(pyqDevicePlan.getDomain());

        if(StringUtils.isBlank(pyqJobSendDao.getItemid())){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择商品");
        }

        List<String> imgList = pyqJobSendDao.getImgList();

        if(imgList != null && imgList.size() > 9){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "图片数量不能大于9张");
        }

        //后台异步调用单个商品发送朋友圈接口
        pyqGoodsSyncService.addJobSync(pyqJobSendDao, deviceUniqueIdList);

        try{
            Thread.sleep(500);
        }catch (Exception e){

        }

    }
}
